const { default: axios } = require('axios')
const strong = require('./set')
const urlNavtive = 'https://fc-mp-d55e8f18-e485-4a28-a1b6-74998af468fc.next.bspapp.com'
const url = `https://jszyapi.com/api.php/provide/vod/at/json`
const db = require('./mysql')

async function copyPage(page, h) {
  return new Promise(async (resolve, rej) => {
    let res = {}
    try {
      res = await axios(`${url}?ac=detail&pg=${page}&h=${h}`)
      resolve(res.data)
    } catch (e) {
      resolve(await copyPage(page))
    }
  })
}

function parseListData(e) {
  let data = []
  for (let v of e) {
    v.vod_play_from = v.vod_play_from.split('$$$')
    v.vod_play_url = v.vod_play_url.split('$$$')
    for (let i in v.vod_play_url) {
      v.vod_play_url[i] = v.vod_play_url[i].split('#')
      for (let i2 in v.vod_play_url[i]) {
        let v2 = v.vod_play_url[i][i2]
        v2 = v2.split('$')
        v.vod_play_url[i][i2] = {
          name: v2[0],
          url: v2[1]
        }
      }
    }
    v.vod_play_url = v.vod_play_url[1]
    v.vod_pubdate = new Date(v.vod_pubdate).getTime() || 946627200000

    data.push(v)
  }
  return data
}

async function pushVideo(list) {
  let json = strong.get()
  try {
    for (let v of list) {
      let s = (await db.query(`select vod_id from videos where vod_id=?`, [v.vod_id]))[0]
      if (s.length > 0) {
        await db.query(`delete from videos where vod_id=?`, [v.vod_id])
      }
      await db.query(`insert into videos values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, [
        0,
        v.vod_id,
        v.type_id,
        v.vod_name,
        v.vod_status,
        v.vod_tag,
        v.vod_class,
        v.vod_pic,
        v.vod_blurb,
        v.vod_remarks,
        v.vod_pubdate,
        v.vod_area,
        v.vod_lang,
        v.vod_year,
        v.vod_time_add,
        parseFloat(v.vod_douban_score),
        v.vod_content,
        JSON.stringify(v.vod_play_url),
        v.type_name
      ])
    }
  } catch (error) {
    console.log({ error })
    pushVideo(list)
  }
  return true
}

let nextTimer = null

async function reptilePage(itPage, h) {
  let json = strong.get()
  json.log.splice(0, 0, `${new Date().getTime()}|开始拷贝${itPage}页`)
  strong.set(json)
  console.log(`${new Date().getTime()}|开始拷贝${itPage}页`)

  const pageData = await copyPage(itPage, h)
  const list = parseListData(pageData.list)

  json.log.splice(0, 0, `${new Date().getTime()}|开始上传${itPage}页`)
  strong.set(json)
  console.log(`${new Date().getTime()}|开始上传${itPage}页`)

  await pushVideo(list)

  json.log.splice(0, 0, `${new Date().getTime()}|${itPage}/${pageData.pagecount}页结束`)
  json.log.splice(20, 9999999999)
  strong.set(json)
  console.log(`${new Date().getTime()}|${itPage}/${pageData.pagecount}页结束`)

  return pageData.pagecount
}

async function reptile() {
  if (nextTimer) {
    clearTimeout(nextTimer)
    nextTimer = null
  }
  let json = strong.get()
  let itPage = 1
  let h = json.h
  let ps = []
  let allLen = 5
  while (true) {
    if (ps.length <= allLen) {
      ps.push(reptilePage(itPage, h))

      if (ps.length == allLen) {
        let d = await Promise.all(ps)
        ps = []
        if (itPage > d[0]) break
      }
    }

    itPage++
  }

  setTimeout(() => {
    reptile()
  }, json.d)
}

reptile()

module.exports = {
  reptile
}

// pushVideo([])
